package org.smth.search.query.impl;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Searcher;
import org.smth.search.config.IndexerConfig;
import org.smth.search.query.QueryProvider;
import org.smth.search.query.SearchRequest;

import java.io.IOException;

@Singleton
public class StaticQueryProviderImpl implements QueryProvider {

	@Inject
	private IndexerConfig config;

	private Searcher searcher;

	public Searcher getIndexSearcher() throws IOException {
		if (searcher == null) {
			synchronized (this) {
				if (searcher == null) {
					searcher = new IndexSearcher(config.getIndexFilePath());
				}
			}
		}
		return searcher;
	}

	public <T> T executeQuery(SearchRequest<T> request) {
		try {
			return request.search(getIndexSearcher());
		} catch (Throwable t) {
			RuntimeException e;
			if (t instanceof RuntimeException) {
				e = (RuntimeException) t;
			} else {
				e = new RuntimeException(t);
			}
			throw e;
		}
	}

}
